package com.ages.graphics;

import javax.media.opengl.*;
import com.sun.opengl.util.texture.*;
import com.sun.opengl.util.texture.TextureIO;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import javax.imageio.ImageIO;

public class TextureLoader {

    /**
     * Texture loader utilizes JOGL's provided utilities to produce a texture.
     *
     * @param fileName relative filename from execution point
     * @return a texture binded to the OpenGL context
     */
    public Texture load(TextureData td) {
        Texture text = null;
//                DisplaylistManager.getDrawable().getContext().makeCurrent();
        try {
//            double time = System.currentTimeMillis();


            text = TextureIO.newTexture(td);


//            System.out.println("time to load tex into graphics card:" + (System.currentTimeMillis() - time));
            text.setTexParameteri(GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
            text.setTexParameteri(GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
        } catch (Exception e) {
            System.out.println("Error:" + e.getMessage());
            e.printStackTrace();
            System.out.println("Error loading texture ");
        }
        return text;
    }

    	public Texture oldLoad(String fileName){
		Texture text = null;
		try{
            BufferedImage bi = ImageIO.read(getClass().getResource(fileName));
            text = TextureIO.newTexture(bi, true);
			text.setTexParameteri(GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
			text.setTexParameteri(GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
		}catch(Exception e){
			System.out.println(e.getMessage());
			System.out.println("Error loading texture " + fileName);
		}
		return text;
	}

//    public Texture loadWithHue(TextureData td, float hue) {
//        Texture text = null;
//        try {
//            BufferedImage bi = ImageIO.read(getClass().getResource(fileName));
//            Raster raster = bi.getData();
//            WritableRaster wr = bi.getRaster();
//            for (int x = 0; x < wr.getWidth(); x++) {
//                for (int y = 0; y < wr.getHeight(); y++) {
//                    int[] rgba = new int[4];
//                    int[] pixel = new int[4];
//                    wr.getPixel(x, y, pixel);
//                    pixel = PixelOperation.changeHue(pixel, hue);
//                    wr.setPixel(x, y, pixel);
//                }
//            }
//            bi.setData(wr);
//            text = TextureIO.newTexture(bi, true);
//            text.setTexParameteri(GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
//            text.setTexParameteri(GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//            System.out.println("Error loading texture " + fileName);
//        }
//        return text;
//    }
}
 
